import React, { Component } from 'react'
import { Button, Tooltip, Input, Tree, Menu, Form, message, Modal, Card, Alert, Tag } from 'antd'
import styles from '../index.less'
import { Scrollbars } from 'react-custom-scrollbars';
import { formatMessage } from 'umi-plugin-locale';
import { ModalForm, ProFormText, ProFormSelect } from '@ant-design/pro-form';
import { UsergroupAddOutlined, UserAddOutlined, UserSwitchOutlined, EditOutlined, DeleteOutlined, UngroupOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { connect } from 'dva';
import { updateGroup, deleteGroup, deleteDevice, updateDevice } from '@/services/group';

import Create from './Create'
import CreateTmp from './CreateTmp'
import AddDevice from './AddDevice'


const { Search } = Input

const groupMenu = [
    { key: 'edit', icon: <EditOutlined />, disabled: false, title: '编辑' },
    { key: 'delete', icon: <UngroupOutlined />, title: '解散' },
    { key: 'divider' },
    { key: 'add', icon: <UserAddOutlined />, disabled: false, title: '添加成员' }
]
const deviceMenu = [
    { key: 'edit', icon: <UserSwitchOutlined />, disabled: false, title: '切换群组' },
    { key: 'addTmp', disabled: false, icon: <UserAddOutlined />, title: '强拉临时组' },
    { key: 'divider' },
    { key: 'delete', icon: <DeleteOutlined />, title: '移出群组' },
]

@connect(({ unit, group, loading }) => ({
    unit,
    group,
    loading: loading.models.unit,
}))
class Group extends Component {
    state = {
        // 是否显示创建群组表单
        showFormModal: false,
        // 是否显示创建临时组表单
        showTmpFormModal: false,
        // 是否显示修改群组表单
        showUpdateModal: false,
        // 是否显示添加成员表单
        showAddDeviceModal: false,
        // 是否显示切换群组表单
        showUpdateDeviceModal: false,
        // 是否显示右键菜单
        showContextMenu: false,
        // 右键菜单类型
        contextMenuType: 'group',
        contextMenu: groupMenu,
        // 当前选中的群组
        currentGroup: {},
        // 当前选中的执法仪
        currentDevice: {},
        // 已选中的节点
        checkedNodes: [],
        // 设置默认选中的节点
        checkedKeys: [],
        // 右键菜单
        rightClickNodeTreeItem: {
            pageX: "",
            pageY: "",
            id: "",
            categoryName: "",
        },


        targetKeys: [],
        renderCount: 1,
    };

    groupTtimer = null
    componentDidMount() {

        this.loadGroupData()
        this.loopGetGroupData()

        document.addEventListener('click', () => {
            this.setState({
                showContextMenu: false
            });
        })

        this.props.dispatch({
            type: 'unit/fetchUnitAndUser',
            payload: {},
        })
    }

    componentWillUnmount() {
        this.groupTtimer && clearInterval(this.groupTtimer);
        this.setState = (state, callback) => {
            return
        }
    }

    loopGetGroupData() {
        this.groupTtimer && clearInterval(this.groupTtimer);
        this.groupTtimer = setInterval(() => this.loadGroupData(), 5000)
    }

    loadGroupData() {
        this.props.dispatch({
            type: 'group/fetchGroupTree',
        })
    }

    onRightClick = e => {
        this.setState({
            showContextMenu: true,
            contextMenuType: e.node.type,
            contextMenu: e.node.type === 'group' ? groupMenu : deviceMenu,
            currentGroup: e.node.type === 'group' ? { id: e.node.key, groupName: e.node.title } : {},
            currentDevice: e.node.type === 'device' ? e.node : {},
            rightClickNodeTreeItem: {
                pageX: e.event.pageX,
                pageY: e.event.pageY,
            }
        });
    };
    // 自定义右键菜单内容

    menuHeight = 30
    getContextMenu = () => {

        let pureMenu = this.state.contextMenu.filter(item => {
            return item.key != 'divider'
        })
        const { pageX, pageY } = { ...this.state.rightClickNodeTreeItem };
        const clientH = document.body.clientHeight;
        const menuHeight = this.menuHeight * pureMenu.length
        let y = pageY + menuHeight > clientH ? pageY - menuHeight : pageY
        const tmpStyle = {
            position: "fixed",
            left: `${pageX}px`,
            top: `${y}px`,
            borderRight: 0,
            boxShadow: '0 3px 6px rgba(0, 0, 0, .3)',
            padding: '4px 0'
        };
        return (
            <Menu style={tmpStyle} className={styles.contextMenu} onClick={this.onContextMenuClick.bind(this)}>
                {
                    this.state.contextMenu.map((item, idx) => {
                        return item.key == 'divider' ? <Menu.Divider key={idx} /> : (
                            <Menu.Item type={'group'} disabled={item.disabled} key={item.key} style={{ height: this.menuHeight + 'px', margin: 0, lineHeight: this.menuHeight + 'px' }}>
                                {item.icon} {item.title}
                            </Menu.Item>
                        )
                    })
                }
            </Menu>
        );
    };

    // 右键菜单操作
    onContextMenuClick = ({ item, key }) => {
        const type = this.state.contextMenuType
        if (type === 'group') {
            if (key === 'edit') {
                this.showUpdateGroup()
            } else if (key === 'delete') {
                this.deleteGroup()
            } else if (key === 'add') {
                this.showAddDevice()
            }
        } else {
            if (key === 'delete') {
                this.deleteDevice()
            } else if (key === 'edit') {
                this.showUpdateDevice()
            } else if (key === 'addTmp') {
                this.showCreateTmpGroup()
            }
        }
    }
    onChange = e => {
        const { value } = e.target;
    };

    // 显示隐藏弹框
    showCreateGroup() {
        this.setState({ showFormModal: true })
    }
    hideCreateGroup() {
        this.setState({ showFormModal: false })
    }
    showCreateTmpGroup() {
        this.setState({ showTmpFormModal: true })
    }
    hideCreateTmpGroup() {
        this.setState({ showTmpFormModal: false })
    }

    showUpdateGroup() {
        this.setState({ showUpdateModal: true })
    }
    hideUpdateGroup() {
        this.setState({ showUpdateModal: false })
    }
    showAddDevice() {

        this.props.dispatch({
            type: 'group/fetchDetail',
            payload: { id: this.state.currentGroup.id },
            callback: ({ code, data }) => {
                if (code === 0) {
                    this.setState({ showAddDeviceModal: true })
                }
            }
        })

    }
    hideAddDevice() {
        this.setState({ showAddDeviceModal: false })
    }
    showUpdateDevice() {
        this.setState({ showUpdateDeviceModal: true })
    }
    hideUpdateDevice() {
        this.setState({ showUpdateDeviceModal: false })
    }

    onCheck = (selectedKeys, e) => {
        let nodes = e.checkedNodes.filter(item => {
            return item.type !== 'group'
        })
        this.setState({
            checkedNodes: nodes
        })
    }

    removeDevice(removeNode) {
        const checkedNodes = this.state.checkedNodes.filter(node => node !== removeNode);
        const checkedKeys = checkedNodes.map(node => {
            return node.key
        })
        this.setState({
            checkedNodes,
            // checkedKeys
        })
        // 
    }
    // 修改群组
    async saveUpdateGroup(values) {
        const result = await updateGroup({
            id: this.state.currentGroup.id,
            groupName: values.groupName
        })
        if (result.code === 0) {
            message.success("群组修改成功")
            this.loadGroupData()
            this.hideUpdateGroup()
        } else {
            message.error("群组修改失败")
        }
    }

    /**
     * 删除群组
     */
    deleteGroup() {
        Modal.confirm({
            title: '您确定解散该群组吗？',
            icon: <ExclamationCircleOutlined />,
            onOk: async () => {
                const result = await deleteGroup({
                    id: this.state.currentGroup.id,
                })
                if (result.code === 0) {
                    message.success("群组解散成功")
                    this.loadGroupData()
                } else {
                    message.error("群组解散失败")
                }
            },
            onCancel() {
            },
        })
    }

    // 删除群组成员
    async deleteDevice(values) {
        Modal.confirm({
            title: '您确定移出该群组成员吗？',
            icon: <ExclamationCircleOutlined />,
            onOk: async () => {
                const device = this.state.currentDevice
                const result = await deleteDevice({
                    groupId: device.groupId,
                    device: device.sn,
                })
                if (result.code === 0) {
                    message.success("群组成员已经移出")
                    this.loadGroupData()
                } else {
                    message.error("群组成员移出失败")
                }
            },
            onCancel() {
            },
        })
    }

    // 切换群组
    async saveSwitchGroup(values) {
        const device = this.state.currentDevice
        const result = await updateDevice({
            groupId: device.groupId,
            device: device.sn,
            newGroupId: values.newGroupId
        })
        if (result.code === 0) {
            message.success("切换群组成功")
            this.hideUpdateDevice()
            this.loadGroupData()
        } else {
            message.error("切换群组失败")
        }
    }

    onChangeTransfer(keys) {
        this.setState({
            targetKeys: keys
        })
    }


    render() {


        // const generateTree = (treeNodes = []) => {
        //     return treeNodes.map(({ children, ...props }) => {

        //         const title = <span>
        //             {props.title}
        //             {
        //                 props.isTmp === 1 && (
        //                     <span style={{ paddingLeft: 5, color: '#bbb' }}>[临时组]</span>    
        //                 )
        //             }
        //         </span>;

        //         return {
        //             ...props,
        //             title,
        //             children: generateTree(children),
        //         }
        //     })
        // }

        const groupTree = this.props.group.groupTree || []
        const selectGroup = groupTree.map((item, idx) => {
            return {
                label: item.title,
                value: item.value,
            }
        })

        return (
            <div className={styles.leftSider}>
                <div className={styles.orgList}>
                    <div className={`${styles.item} flex inline-item justify-content-between`} style={{ marginBottom: '16px' }} >
                        <Search allowClear={true} placeholder={formatMessage({ id: 'live.search_placeholder' })} onChange={this.onChange} />
                        <Tooltip placement="top" title="创建群组">
                            <Button style={{ marginLeft: '5px', width: 40 }} onClick={this.showCreateGroup.bind(this)} type="primary" icon={<UsergroupAddOutlined />}></Button>
                        </Tooltip>
                    </div>

                    <div className={styles.tree}>
                        <Scrollbars
                            autoHide
                            autoHideTimeout={1000}
                            autoHideDuration={200}
                            style={{ height: '100%' }}
                        >
                            <Tree
                                style={{ marginLeft: '5px' }}
                                blockNode
                                checkable
                                // onSelect={this.onSelect}
                                onCheck={this.onCheck.bind(this)}
                                treeData={groupTree}
                                onRightClick={this.onRightClick.bind(this)}
                            />

                        </Scrollbars>
                    </div>
                    {this.state.showContextMenu === true && this.getContextMenu()}


                    {/* 创建群组 */}
                    <Create
                        {...this.props}
                        visible={this.state.showFormModal}
                        onCancel={this.hideCreateGroup.bind(this)}
                        callback={this.loadGroupData.bind(this)}
                    />
                    {/* 添加群组成员 */}
                    <AddDevice
                        {...this.props}
                        visible={this.state.showAddDeviceModal}
                        onCancel={this.hideAddDevice.bind(this)}
                        callback={this.loadGroupData.bind(this)}
                        values={{ ...this.state.currentGroup }}
                    />
                    {/* 创建临时组 */}
                    <CreateTmp
                        {...this.props}
                        visible={this.state.showTmpFormModal}
                        onCancel={this.hideCreateTmpGroup.bind(this)}
                        callback={this.loadGroupData.bind(this)}
                        checkedNodes={this.state.checkedNodes}
                    />

                    <ModalForm title="修改群组"
                        visible={this.state.showUpdateModal}
                        width={400}
                        modalProps={{
                            destroyOnClose: true,
                            onCancel: this.hideUpdateGroup.bind(this),
                        }}
                        onFinish={async (values) => {
                            this.saveUpdateGroup(values)
                        }}
                        initialValues={{
                            ...this.state.currentGroup
                        }}
                    >
                        <ProFormText width="md" name="groupName" label="群组名称" placeholder="请输入群组名称"
                            rules={[{ required: true }]} />
                    </ModalForm>

                    <ModalForm title="切换群组"
                        visible={this.state.showUpdateDeviceModal}
                        width={400}
                        modalProps={{
                            destroyOnClose: true,
                            onCancel: this.hideUpdateDevice.bind(this),
                        }}
                        onFinish={async (values) => {
                            this.saveSwitchGroup(values)
                        }}
                        initialValues={{
                        }}
                    >
                        {/* <ProFormText width="md" name="groupName" label="当前群组" disabled={true} /> */}
                        <ProFormSelect
                            label="目标群组"
                            width="md"
                            options={selectGroup}
                            name="newGroupId"
                        />
                    </ModalForm>
                </div>
            </div>
        )
    }
}
export default Group;
